# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import math
import torch_npu
import torch

# from vllm.platforms import current_platform

from utils import dense_to_crow_col, get_head_sliding_step, get_sparse_attn_mask

# IS_COMPUTE_8_OR_ABOVE = current_platform.has_device_capability(80)

# if IS_COMPUTE_8_OR_ABOVE:
#     from .blocksparse_attention_kernel import blocksparse_flash_attn_varlen_fwd
from block_sparse_attn import blocksparse_flash_attn_varlen_fwd
IS_COMPUTE_8_OR_ABOVE = False
DEVICE = "npu"

class LocalStridedBlockSparseAttn(torch.nn.Module):

    def __init__(
        self,
        n_heads,
        max_seqlen,
        local_blocks,
        vert_stride,
        block_size,
        device=None,
        dtype=None,
        homo_head=False,
        active_head_range=None,
        q_block_size=None,
        use_spda=None,
    ):
        super().__init__()
        # use_sqda: 是否 use Scaled Dot Product Attention
        # 是否使用缩放点积注意力
        if use_spda is None:
            # use_spda = current_platform.is_rocm() or \
            #             current_platform.is_cpu() or not \
            #             IS_COMPUTE_8_OR_ABOVE
            use_spda = False
        # device = device or (torch.cuda.current_device()
        #                     if current_platform.is_cuda_alike() else "cpu")
        device = DEVICE
        device = torch.device(device)
        # NOTE: vllm CPU backend support BF16 instead of FP16.
        # dtype = dtype or (torch.bfloat16 if IS_COMPUTE_8_OR_ABOVE
        #                   or device.type == "cpu" else torch.half)
        dtype = torch.half

        self.n_heads = n_heads
        self.max_seqlen = max_seqlen
        self.local_blocks = local_blocks
        self.vert_stride = vert_stride
        self.use_spda = use_spda
        self.dtype = dtype
        self.device = device
        self.block_size = block_size
        self.q_block_size = q_block_size
        self.homo_head = homo_head
        self.active_head_range = active_head_range
        self.head_sliding_step = get_head_sliding_step(n_heads, vert_stride,
                                                       homo_head)

        sparse_layout, sparse_pattern, self.dense_attn_mask = (
            self.get_attn_pattern(dtype, device))

        # 进行块切分操作
        if q_block_size is not None and q_block_size != block_size:
            # 将多个小块合并成一个大块
            if q_block_size > block_size:
                # 确保是整数倍
                assert q_block_size % block_size == 0
                blocks_to_merge = q_block_size // block_size
                shape = sparse_pattern.shape
                # 进行拆分操作 将连续的blocks_to_merge个小查询块合成一个大查询块
                sparse_pattern = sparse_pattern.view(shape[0], -1,
                                                     blocks_to_merge,
                                                     shape[-1])
                # 在维度2进行融合操作，将分组内的多个小块掩码合并成一个大块掩码
                sparse_pattern = sparse_pattern.sum(2)
                # 按照sparse_pattern重新生成sparse_layout
                sparse_layout = dense_to_crow_col(sparse_pattern)
            else:
                raise ValueError(
                    "Does not support smaller q_block_size. It will be slower."
                )

        self.sparse_layout = sparse_layout

    '''
    sparse_layout: CSR格式的[crow, col]元组 crow [n_heads, num_blocks_q + 1] col [n_heads, total_valid_blocks]
    作用 提供高效的稀疏注意力布局 避免存储整个O(n^2)稠密矩阵 只记录非零位置
    sparse_pattern: 形状[num_heads, num_blocks_q, num_blocks_k] 或 同质头[1, num_block_q, num_block_k]
    作用 作为中间表示 用于验证稀疏布局(CSR)的正确性 或在调试/测试中重建稠密视图
    dense_attn_mask: 形状[n_heads, q_len, max_seqlen]
    作用 提供 完整 token 级掩码 用于不支持稀疏内核的路径(如 PyTorch 的 scaled_dot_product_attention,SPDA)。
         它确保稀疏约束在 token 级生效，同时保持因果性(生成任务不泄露未来)。
    '''
    def get_attn_pattern(self, dtype, device):
        # dense_mask_type = bias, -inf / 0 (-inf 屏蔽注意力，softmax概率为0)
        # dense_mask_type = binary 0 / 1 (0屏蔽  1允许)
        sparse_layout, sparse_pattern, dense_attn_mask = get_sparse_attn_mask(
            self.n_heads,
            self.max_seqlen,
            self.max_seqlen,
            dtype,
            device,
            block_size=self.block_size,
            local_blocks=self.local_blocks,
            vert_stride=self.vert_stride,
            homo_head=self.homo_head,
            return_dense=self.use_spda,
            dense_mask_type="bias",
        )
        if (not self.homo_head) and (self.active_head_range is not None):
            assert isinstance(self.active_head_range, tuple)
            assert (len(self.active_head_range) == 2)
            h_start, h_end = self.active_head_range
            # 这里进行了裁剪 作用 裁剪稀疏布局，只保留活跃头的掩码，减少内存和计算
            sparse_layout = tuple(x[h_start:h_end] for x in sparse_layout)
            # SPDA 需要稠密掩码 因此只在该路径下裁剪
            if self.use_spda:
                # 同步裁剪稠密掩码，确保一致性
                dense_attn_mask = dense_attn_mask[h_start:h_end]
        return sparse_layout, sparse_pattern, dense_attn_mask

    def varlen_attn(self,
                    q,
                    k,
                    v,
                    cu_seqlens_k,
                    cu_seqlens_q=None,
                    sm_scale=None):
        """
        q, k, v: shape = (num_tokens, num_heads_q/kv, head_size).
        Support grouped attention, with `q[:, i*r:(i*r + r)]`
        is correspondent to `k[:, i]`, where `r` is the q/k ratio.
        cu_seqlens_k: shape=(batch_size + 1,),
        indicating segment of samples,
        e.g., `k[cu_seqlen[i]:cu_seqlne[i+1]]` is q of sample i
        cu_seqlens_q: shape=(batch_size + 1, ).
        Default None: same as cu_seqlens_k for prefilling or
        [0, 1, .., batch_size] for decoding.
        The only case you need to specify is when q is a mix of
        prefilling and decoding.
        sm_scale: softmax scale, default to 1/sqrt(head_size).

        return: tensor of shape as q.
        """
        # assert (
        #     IS_COMPUTE_8_OR_ABOVE
        # ), "Requires compute capability of 8 or above (Ampere or newer) to use \
        #     Triton kernel."

        # 获取缩放参数
        sm_scale = sm_scale or 1.0 / math.sqrt(q.size(-1))

        return blocksparse_flash_attn_varlen_fwd(
            q,
            k,
            v,
            cu_seqlens_k,
            cu_seqlens_q,
            sm_scale,
            self.sparse_layout,
            block_size=self.block_size,
            q_block_size=self.q_block_size,
            max_seqlen=self.max_seqlen,
        )

    # 类方法 无需类实例即可调用
    @staticmethod
    def transpose_and_pad(x, cu_seqlens, maxlen, head_repeats=1):
        """
        :param x: (total_tokens, n_heads, head_size)
        :return: (batch, n_heads, length, head_size)
        """
        # 进行padding操作
        # 形状: [batch_size, num_size, head_repeats, maxlen, head_size]
        x_padded = x.new_empty(
            len(cu_seqlens) - 1, x.size(1), head_repeats, maxlen, x.size(2))
        # 数据回到cpu端
        cu_seqlens = cu_seqlens.cpu()
        # cu_seqlens[:-1]和cu_seqlens[1:] 是进行切分数组的操作
        # 逐批次处理变长序列，提取每个批次的 token 范围 [s:e]。
        for i, (s, e) in enumerate(zip(cu_seqlens[:-1], cu_seqlens[1:])):
            # x[s:e] 形状是 [seq_len_i, n_heads, head_size]
            # transpose操作 [n_heads, seq_len_i, head_size]
            # unsqueeze(1) [n_heads, 1, seq_len_i, head_size]
            # x_padded[i, :, :, :e - s] [n_heads, head_repeats, seq_len_i, head_size]
            x_padded[i, :, :, :e - s].copy_(x[s:e].transpose(0,
                                                             1).unsqueeze(1))
        # 将第一维和第二维进行平展操作
        # (batch, n_heads, head_repeats, maxlen, head_size)
        # (batch, n_heads * head_repeats, maxlen, head_size)
        return x_padded.flatten(1, 2)

    # transpose_and_pad的反操作
    @staticmethod
    def transpose_and_unpad(x_padded, cu_seqlens):
        """
        :param x_padded: (batch, n_heads, length, head_size)
        :return: (total_tokens, n_heads, head_size)
        """
        cu_seqlens = cu_seqlens.cpu()
        total_n_tokens = cu_seqlens[-1]
        x = x_padded.new_empty(total_n_tokens, x_padded.size(1),
                               x_padded.size(3))
        for i, (s, e) in enumerate(zip(cu_seqlens[:-1], cu_seqlens[1:])):
            x[s:e].copy_(x_padded[i, :, :e - s].transpose(0, 1))
        return x

    # 进行Scaled Dot Product Attention
    def spda(self, q, k, v, cu_seqlens_k, cu_seqlens_q=None, sm_scale=None):
        """For CPU, V100 or other older GPUs.
        NOTE: torch SPDA supports nested tensor,
        but seems extremely slow. Choose to pad instead.
        """
        assert (cu_seqlens_q is None or
                (cu_seqlens_q
                 == cu_seqlens_k).all()), "Can only handle prompt with SPDA."
        assert q.size(0) == k.size(0), "can only handle prompt with SPDA."

        # 支持GQA计算
        assert q.size(1) % k.size(1) == 0
        # q和kv的头重复比率
        q_k_ratio = q.size(1) // k.size(1)
        sm_scale = sm_scale or 1.0 / math.sqrt(q.size(-1))
        # cu_seqlens 序列的累积长度
        cu_seqlens = cu_seqlens_k.cpu()
        # 获取批次中最大的序列长度
        maxlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()

        if (self.dense_attn_mask.dtype != q.dtype
                or self.dense_attn_mask.device != q.device):
            _, _, self.dense_attn_mask = self.get_attn_pattern(
                q.dtype, q.device)
        # dense_attn_mask 形状[q_heads, max_seqlen, max_seqlen]
        # attn_mask形状 [1, q_heads, maxlen, maxlen]
        attn_mask = self.dense_attn_mask[None, :, :maxlen, :maxlen]

        # q2形状 [batch, q_heads, maxlen, head_size]
        q2 = self.transpose_and_pad(q, cu_seqlens, maxlen, 1)
        # q_k_ratio 进行重复复制操作
        # k2, v2：[batch, q_heads, maxlen, head_size] q_heads = kv_heads * q_k_ratio
        k2, v2 = (self.transpose_and_pad(x, cu_seqlens, maxlen, q_k_ratio)
                  for x in [k, v])
        # 这里调用torch的scaled_dot_product_attention操作
        # sqda_output [batch, q_heads, maxlen, head_size]
        spda_output = torch.nn.functional.scaled_dot_product_attention(
            q2, k2, v2, attn_mask=attn_mask, scale=sm_scale)
        # 进行逆操作 [total_tokens, q_heads, head_size]
        return self.transpose_and_unpad(spda_output, cu_seqlens)

    # 进行计算
    def forward(self, q, k, v, cu_seqlens_k, cu_seqlens_q=None, sm_scale=None):
        """Dispatch to `varlen_attn` (Ampere or newer) or
        `self.spda`(cpu, Volta, Turing or older)based on
        the type of device used and cuda compute capability.

        q, k, v: shape = (num_tokens, num_heads_q/kv, head_size).
                Support grouped attention, with `q[:, i*r:(i*r + r)]`
                is correspondent to `k[:, i]`, where `r` is the q/k ratio.
        cu_seqlens_k: shape=(batch_size + 1,), indicating segment of samples,
                    e.g., `k[cu_seqlen[i]:cu_seqlne[i+1]]` is q of sample i
        cu_seqlens_q: shape=(batch_size + 1, ).
                    Default None: same as cu_seqlens_k for prefilling or
                    [0, 1, .., batch_size] for decoding.
                    The only case you need to specify
                    is when q is a mix of prefilling
                    and decoding.
        sm_scale: softmax scale, default to 1/sqrt(head_size).

        return: tensor of shape as q.
        """
        assert k.dim() == 3
        # 使用老版本的spda操作，来兼容旧硬件设备 包括CPU等等
        if self.use_spda:
            return self.spda(
                q,
                k,
                v,
                cu_seqlens_k,
                cu_seqlens_q=cu_seqlens_q,
                sm_scale=sm_scale,
            )
        # 进入主要操作步骤了
        return self.varlen_attn(q,
                                k,
                                v,
                                cu_seqlens_k,
                                cu_seqlens_q=cu_seqlens_q,
                                sm_scale=sm_scale)